/**
 * Created by parth.upadhye on 21/07/2014.
 */

function partialPath()
{
    return "partials/";
}

var creatorTopicModel = {"uuid": "", "title": "", "descriptor": "", "category": "", "tags": "",
    "links": [{"name": "", "url": ""}],
    "items": [{"text": "", "title": "", "type": "text" } ],
    "references": [{"name": "", "url": ""}] };

var questionModel = {"text": "", "title": "", "type": "text" };
var linkModel = {"name": "", "url": ""};

var topicApp = angular.module("topicApp",
    ['ngRoute', 'creatorApp'] );

var creatorApp = angular.module("creatorApp", [
    'ngRoute', 'topicDirectives'
]);

creatorApp.controller("LoginController", ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
    BaseController ( $scope );
}]);

creatorApp.controller("CreatorTopicsController", ['$scope', '$routeParams', '$http',
    function ($scope, $routeParams, $http) {

        BaseController ( $scope );

        $scope.showTopicBeingEdited = false;
        $scope.showTopicsSearch = false;
        $scope.showTopicsHome = true;

        $scope.creatorTopic = angular.copy( creatorTopicModel );
        $scope.topicsList = [];
        $scope.tagsInCategory = [];
        $scope.selectedTags="";
        $scope.creatorTopicTags="";

        var array = $routeParams.params.split("&&");
        $scope.selectedCategory = "";
        if ( array[0] != ""  ) {
            selectedCategoryUuid = array[0];
        }
        for (var c = 0; c < categories.length; c++)
        {
            if ( categories[c].uuid == selectedCategoryUuid )
            {
                $scope.selectedCategory = categories[c].name;
            }
        }

        $scope.topicUuid = array[2];
        $scope.topicUncommitted = null;

        $scope.getTagsInCategory = function ()
        {
            $http.get('http://localhost:3001/GetTagsForCategory?category='+selectedCategoryUuid)
                .success(function(data) {
                    var obj =  data.tags;
                    $scope.tagsInCategory = data.tags;
                }
            );
        }

        $scope.getTagsInCategory ();

        $scope.getTopicsForTags = function ( selectedCategory, searchTags )
        {
            $http.get('http://localhost:3001/GetTopics?tags=' + searchTags.join(", ") )
                .success(function(data) {
                    var obj = data;
                    $scope.topicsList = data;
                    })
                .error(function(data, status, headers, config) {
                    var obj = data;
                });
        }
        $scope.getTopicFromList = function ( tid )
        {
            $scope.topicUuid = tid;
            $scope.showTopic();
        }


        $scope.getFormInstructs = function ( object )
        {
            window.alert("It is a good idea to provide users with links to get them started on research. You can give the url a friendly name.");
        }

        $scope.addQuestion = function ()
        {
            $scope.creatorTopic.items.push ( angular.copy( questionModel ) );
        }

        $scope.addLink = function ()
        {
            $scope.creatorTopic.links.push ( angular.copy( linkModel ) );
        }

        $scope.showTopic = function ()
        {
            if ( $scope.topicUuid == undefined || $scope.topicUuid.length == 0 || $scope.topicUuid == "undefined")
            {


            } else {
                $scope.topicBeingEdited = true;
                $scope.getTopicEditorPage();
                //$http.get('http://localhost:3001/GetTopic?topic='+ $scope.topicUuid)
                $http.get('data/topic.json')
                    .success(function(data) {
                        $scope.creatorTopic = data;
                        $scope.topicUncommitted = angular.copy( $scope.creatorTopic );
                    })
                    .error(function(data, status, headers, config) {
                        $scope.creatorTopic = angular.copy( $scope.topicUncommitted );
                    });
            }
        }

        $scope.getTopicsHomePage = function ()
        {
            $scope.showTopicBeingEdited = false;
            $scope.showTopicsSearch = false;
            $scope.showTopicsHome = true;
        }
        $scope.getTopicsSearchPage = function ()
        {
            $scope.showTopicBeingEdited = false;
            $scope.showTopicsSearch = true;
            $scope.showTopicsHome = false;
        }

        $scope.getTopicEditorPage = function ()
        {
            $scope.creatorTopic = angular.copy( creatorTopicModel );
            $scope.creatorTopic.uuid = null;
            $scope.creatorTopicTags="";
            $scope.showTopicBeingEdited = true;
            $scope.showTopicsSearch = false;
            $scope.showTopicsHome = false;
            $scope.$apply();
        }


        $scope.save = function()
        {
            $scope.creatorTopic.category = selectedCategoryUuid;
            $scope.creatorTopic.tags = $scope.createTopicTags ( $scope.creatorTopicTags, $scope.tagsInCategory );

            $scope.creatorTopic = $scope.cleanCreatorTopic ( $scope.creatorTopic );

            $http({method: 'POST', url: 'http://localhost:3001/CreateTopic', data: "json="+JSON.stringify($scope.creatorTopic ),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
                .success( function(data) {

                    if ( $scope.creatorTopic.descriptor == null || $scope.creatorTopic.descriptor.length == "" )
                    {
                        $scope.creatorTopic.descriptor = $scope.creatorTopic.title;
                    }

                    if ( $scope.creatorTopic.uuid == null || $scope.creatorTopic.uuid == "" )
                    {
                        var uuidInt = parseInt(data);
                        $scope.creatorTopic.uuid = uuidInt;
                        var topic = angular.copy( $scope.creatorTopic );
                        $scope.topicsList.push( topic );
                    }

                    $scope.topicUncommitted = angular.copy( $scope.creatorTopic);
                    $scope.topicBeingEdited = false;
                    $scope.$apply();
                } )
                .error( function(data, status, headers, config) {
                        $scope.creatorTopic = angular.copy( $scope.topicUncommitted );
                        $scope.topicBeingEdited = false;
                        $scope.$apply();
                    } )
        }

        $scope.cleanCreatorTopic = function ( topic )
        {
            var items = [];
            for ( var i=0; i < topic.items.length; i++ )
            {
                var item = { text: topic.items[i].text, title: topic.items[i].title, type: topic.items[i].type };
                items.push ( item );
            }
            topic.items = items;

            var links = [];
            for ( var i=0; i < topic.links.length; i++ )
            {
                var link = { text: topic.links[i].text, url: topic.links[i].url };
                links.push ( link );
            }
            topic.links = links;

            return topic;
        }

        $scope.doNotSave = function ()
        {
            angular.copy( $scope.topicUncommitted, $scope.creatorTopic);
            $scope.topicBeingEdited = false;
            $scope.$apply();
        }


    }]);


creatorApp.controller("CreatorHomeController", ['$scope', '$routeParams', '$location', '$http',
    function ($scope, $routeParams, $location, $http) {

        BaseController ( $scope );

        if ($routeParams.userUuid != "")
        {
            userUuid = $routeParams.userUuid;
        }

        $scope.tagCloudMin = 0;
        $scope.tagCloudMax = 0;
        $scope.tagCloudStep = 0;

        $http.get('http://localhost:3001/GetCategories')
            .success(function(data) {
                categories = data;
                $scope.categories = data;
                createBarCloud( categoriesCloudCanvas, data ,null );
            }
        );
        $http.get('http://localhost:3001/GetTopicsInCategories')
            .success(function(data) {
                $scope.topicsAvailable = data;
                createBarCloud( topicsAvailableCloudCanvas, data ,null );
            }
        );
    }]);

creatorApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/home/:userUuid', {
                templateUrl: partialPath() + 'creator/creatorHome.html',
                controller: 'CreatorHomeController'
            }).
            when('/topics/:params', {
                templateUrl: partialPath() + 'creator/creatorTopics.html',
                controller: 'CreatorTopicsController'
            }).
            otherwise({
                templateUrl: partialPath() + 'creator/creatorLogin.html',
                controller: 'LoginController'
            });
    }]);